var express = require("express");
var router = express.Router();
const jwt = require("jsonwebtoken"); //生成token
// 可以接受图片
const multiparty = require("multiparty");

// 导入model.js
var { UserModel} = require("../model/model");
// 加密密码
const bcrypt = require("bcryptjs");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

// token登录
router.get("/login", async (req, res) => {
  // 接受数据
  let query = req.query;
  console.log(req.ip);
  // 处理数据
  let [data] = await UserModel.find({
    username: query.username,
    password: query.password,
  });

  if (data) {
    let token =
      "Bearer" +
      " " +
      jwt.sign({ username: query.username, password: query.password }, "flag", {
        expiresIn: 100000,
      });
    // 对用户的密码,进行 bcrype 加密，返回值是加密之后的密码字符串
    let pws = bcrypt.hashSync(query.password, 10);
    console.log(pws);
    res.send({
      code: 200,
      msg: "登录成功",
      token,
    });
  } else {
    res.send({
      code: 500,
      data: null,
      message: "用户名或者密码错误",
    });
  }
});

// 用户登录展示
router.post("/user_show", async (req, res) => {
  let data = await UserModel.find({
    username: req.body.username,
    password: req.body.password,
  }).populate({path:'EntryMessage_id',populate:({path:'station_id',populate:[{path:'department_id'}]})})
  .populate('education_experience_id')
  .populate('work_experience_id')
    .exec();
  res.send({
    code: 200,
    msg: "获取登录用户成功",
    data:data[0],
  });
});

// 添加用户
router.post("/add_user", async (req, res) => {
  let body = req.body;
  await UserModel.create(body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

// 修改用户
router.put("/edit_user/:id", async function (req, res) {
  let body = req.body;
  await UserModel.updateOne({ _id: req.params.id }, { $set: body });
  res.send({
    code: 200,
    msg: "修改成功",
  });
});

// 删除用户
router.delete("/del_user/:id", async function (req, res) {
  await UserModel.deleteOne({ _id: req.params.id });
  res.send({
    code: 200,
    msg: "删除成功",
  });
});

// 用户列表
router.get("/user_list", async (req, res) => {
  let pageIndex = req.query.pageIndex;
  let pageSize = req.query.pageSize;
  let username = req.query.username;
  let name = req.query.name;
  console.log(req.query);
  let list = [];
  let total = 0;
  let usernamereg = new RegExp(username, "i");
  let namereg = new RegExp(name, "i");
  list = await UserModel.find({
    $and: [{ username: usernamereg }, { name: namereg }],
  })
    // .populate("role_id")
    .populate({path:'EntryMessage_id',populate:({path:'station_id',populate:[{path:'department_id'}]})})
    .populate('education_experience_id')
    .populate('work_experience_id')
    .skip((pageIndex - 1) * pageSize)
    .limit(pageSize)
    .sort({ times: -1 })
    .exec();
  total = list.length;
  res.send({
    code: 200,
    msg: "展示成功",
    data: list,
    total: total,
  });
});

module.exports = router;
